import { Injectable } from "@nestjs/common";
import { encryptPassword } from "../../utils/cryptogram";
import { UserExistService } from "../user/user.exist.service";
import { JwtService } from "@nestjs/jwt";

@Injectable()
export class AuthService {
  constructor(
    private readonly userExistService: UserExistService,
    private readonly jwtService: JwtService
  ) {
  }

  async validateUser(requestBody: any): Promise<any> {
    //JWT验证: 用户信息校验
    console.log('JWT验证 - Step 2: 用户信息校验');
    let nickName: string = "";
    let phoneNum: string = "";
    let password: string;
    if (requestBody.nickName) {
      nickName = requestBody.nickName;
    }
    if (requestBody.phoneNum) {
      phoneNum = requestBody.phoneNum;
    }
    password = requestBody.password;
    const user = await this.userExistService.userExist({ nickName, phoneNum });
    if (user) {
      const PWSalt = user.PWSalt;
      let hashPW = encryptPassword(password, PWSalt);
      if (user.hashPW === hashPW) {
        const { PWSalt, hashPW, ...result } = user;
        return result;
      }
    }
    return null;
  }

  async login(user: any) {
    //JWT验证: 处理 jwt 签证
    const payload = { username: user.nickName, sub: user.userId };
    console.log('JWT验证 - Step 3: 处理 jwt 签证');
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}